@model string[]

@using Newtonsoft.Json.Linq;
@using SmartStore.Utilities;

@functions {
	private string[] Value
	{
		get
		{
			string[] value = null;
			if (ViewData.Model != null)
			{
				value = ViewData.Model;
			}
			return value;
		}
	}
}

@{
	var id = ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty);
	var name = ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty);
	var widgetProvider = EngineContext.Current.Resolve<IWidgetProvider>();
	var jsonZones = (JObject)widgetProvider.GetAllKnownWidgetZones();

	var areas =
		from p in jsonZones["WidgetZonesAreas"]
		select p;

	var zones = new List<SelectListItem>();
	var userDefinedZones = Value != null ? Value.ToList() : new List<string>();
	var selectedZones = new HashSet<string>(userDefinedZones, StringComparer.OrdinalIgnoreCase);

	// add system zones
	foreach (var area in areas)
	{
		var areaName = area["name"].ToString();
		var areasObj =
			from p in area["zones"]
			select p;

		var groupName = Inflector.Pascalize(T(areaName.ToString()).Text);
		var group = new SelectListGroup { Name = groupName };

		foreach (var zone in areasObj)
		{
			var zoneName = zone.ToString();
			zones.Add(new SelectListItem
			{
				Text = zoneName,
				Value = zoneName,
				Selected = selectedZones.Contains(zoneName),
				Group = group
			});

			// remove item from userdefined zones (it is a system zone)
			userDefinedZones.Remove(zoneName);
		}
	}

	// add userdefined zones to available zones
	var userDefinedGroup = new SelectListGroup { Name = T("Admin.WidgetZones.UserDefined").Text };
	userDefinedZones.Reverse();

	foreach (var zoneName in userDefinedZones)
	{
		zones.Insert(0, new SelectListItem
		{
			Text = zoneName,
			Value = zoneName,
			Selected = true,
			Group = userDefinedGroup
		});
	}

	// get selected items
	var selectedValues = zones.Where(x => x.Selected == true).Select(x => x.Value.ToString()).ToArray();
}

@Html.ListBox("", 
	new MultiSelectList(zones, "Value", "Text", "Group.Name", selectedValues), 
	new { @class = "form-control x-select2-hidden-accessible", multiple = "multiple", size = 1, data_tags = "true", value = Value, name = name, id = id })